﻿using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
using System.Web.ModelBinding;
using AngularStart1.Data;
using AngularStart1.Models;
using TodoApi.Data;

namespace AngularStart1.Api
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class TodosController : ApiController
    {
        readonly static EntityframeworkRepository _repo = new EntityframeworkRepository();

        public HttpResponseMessage Get()
        {
            var todos = _repo.List();
            return Request.CreateResponse(HttpStatusCode.OK, todos);
        }

        public HttpResponseMessage Get(int id)
        {
            var todo = _repo.Get(id);

            if (todo==null)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No Todo found.");
            }
            return Request.CreateResponse(HttpStatusCode.OK, todo);
        }

        [HttpPost]
        public HttpResponseMessage Post(Todo todo)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid data...");
            }

            if (string.IsNullOrWhiteSpace(todo.Description))
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Todo description is required.");
            }

            var addedTodo = _repo.Add(todo);
            return Request.CreateResponse(HttpStatusCode.OK, addedTodo);
        }

        [HttpPut]
        public HttpResponseMessage Put(Todo todo)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid data...");
            }

            if (string.IsNullOrWhiteSpace(todo.Description))
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Todo description is required.");
            }

            var updatedTodo = _repo.Update(todo);
            return Request.CreateResponse(HttpStatusCode.OK, updatedTodo);
        }

        [HttpDelete]
        public HttpResponseMessage Delete(int todoId)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid data...");
            }

            if (todoId==0)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Todo identifier is required.");
            }

            _repo.Remove(todoId);
            //var todos = _repo.List(); //NB: cannot pass result in a http delete command!
            return Request.CreateResponse(HttpStatusCode.OK);
        }

    }
}
